using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using Infragistics.WebUI.UltraWebNavigator;

/// <summary>
/// Summary description for GridPaging
/// </summary>
public class GridPaging
{
    public GridPaging()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public bool DisplayPage(String strPagesetRowID, HtmlForm frmObj)
    {
        GenerateGrid objGG = new GenerateGrid();
        HDDatabase HDD = new HDDatabase();
        security HDS = new security();
        DynamicDisplayI DDI = new DynamicDisplayI();


        string sNoofRecords = HDD.getAcrMemValue("3813ac7202378893", "1"); // added by Jeya Prabha on 17-Sep-2007 to set the number of records displayed
        if (sNoofRecords != "" && sNoofRecords != "0")
            GlobalValues.intNoOfRecordsPerPage = int.Parse(sNoofRecords);

        else
            GlobalValues.intNoOfRecordsPerPage = 8;


        
        bool bRead = false;
        bool bCreate = false;
        bool bEdit = false;
        bool bDelete = false;
        /**********Added By Dhanapal on DEC292010 For Page View Mode**********************/
        DropDownList ddl = (DropDownList)DDI.FindControl(frmObj.Controls, "ddlPageViewType");
        System.Web.UI.HtmlControls.HtmlGenericControl searchpanel = (System.Web.UI.HtmlControls.HtmlGenericControl)DDI.FindControl(frmObj.Controls, "panelSearchholder");
        if (ddl != null)
        {
            string strddlValue = ddl.SelectedValue.ToString();

            if (strddlValue == "LV")
            {
                if (searchpanel != null)
                {
                    /*searchpanel.Visible = true;
                    showandhideDiv(frmObj, "panelDynamicTree", false, DDI);
                    showandhideDiv(frmObj, "panelDynamicGrid", true, DDI);*/
                }
            }
            else if (strddlValue == "TV")
            {
                if (searchpanel != null)
                {
                    searchpanel.Visible = false;
                    showandhideDiv(frmObj, "panelDynamicTree", true, DDI);
                    showandhideDiv(frmObj, "panelDynamicGrid", false, DDI);
                    showandhideDiv(frmObj, "panelDynamicCategory", false, DDI);
                    return DisplayPageWithTree(strPagesetRowID, frmObj, DDI);
                }
            }
            else if (strddlValue == "CV") // Added By Dhanapal On Jan 24 2011
            {
                if (searchpanel != null)
                {
                    searchpanel.Visible = false;
                    showandhideDiv(frmObj, "panelDynamicTree", false, DDI);
                    showandhideDiv(frmObj, "panelDynamicGrid", false, DDI);
                    showandhideDiv(frmObj, "panelDynamicCategory", true, DDI);
                    return DisplayPageWithCategory(strPagesetRowID, frmObj, DDI);
                    //return true;
                }

            }
            else if (strddlValue == "DS") // Added by 'Imran Gani' (copied from RakaTech) on 27-May-2014, for Datasheet
            {
                if (searchpanel != null)
                {
                    searchpanel.Visible = false;
                    showandhideDiv(frmObj, "panelDynamicTree", false, DDI);
                    showandhideDiv(frmObj, "panelDynamicGrid", false, DDI);
                    showandhideDiv(frmObj, "panelDynamicCategory", true, DDI);
                    //return DisplayPageWithCategory(strPagesetRowID, frmObj, DDI);
                    string sMenu = "";
                    if (HttpContext.Current.Request.QueryString["mn"] != null)
                        if (HttpContext.Current.Request.QueryString["mn"].ToString() != "")
                            sMenu = "&mn=" + HttpContext.Current.Request.QueryString["mn"].ToString();
                    HttpContext.Current.Response.Redirect("Datasheet.aspx?pgs_id=" + strPagesetRowID + sMenu);
                    //return true;
                }
            }
        }

        if (searchpanel != null)
        {
            searchpanel.Visible = true;
            showandhideDiv(frmObj, "panelDynamicTree", false, DDI);
            showandhideDiv(frmObj, "panelDynamicCategory", false, DDI);
            showandhideDiv(frmObj, "panelDynamicGrid", true, DDI);

        }
        /*************************************************************/

        HDS.getPagesetRights(strPagesetRowID, ref bRead, ref bCreate, ref bEdit, ref bDelete);
        objGG.loadCurrencySettings();


        bool blnStatus = true;
        if (bRead)
        {
            PageInfoLoad PIL = new PageInfoLoad();
            DataSet dsePageObj = PIL.GetPageSetPagesSrchInfo(strPagesetRowID);
            DataTable dtaPageSet = dsePageObj.Tables["PageSet"];
            DataTable dtaPage = dsePageObj.Tables["Page"];
            DataTable dtaPageKeys = dsePageObj.Tables["PageKeys"];
            DataTable dtaPageSrch = dsePageObj.Tables["PageSrch"];
            DataTable dtaPageControls = dsePageObj.Tables["Page Controls"];

            //Added by srivatsan
            if (dtaPageSrch != null)
            {
                if (dtaPageSrch.Rows.Count > 0)
                {
                    DataRow[] drrsearch = dtaPageSrch.Select("quick_search= 1");
                    if (drrsearch.Length == 0)
                    {
                        Control cBtn = frmObj.FindControl("ctl00$ContentPlaceHolder3$btnfilter");
                        if (cBtn != null)
                        {
                            Button btn = (Button)cBtn;
                            btn.Visible = false;
                        }
                    }
                }
            }

           if (HttpContext.Current.Request["PK"] == null)
            {
                if (frmObj.Page.IsPostBack)
                {
                    if (frmObj.FindControl("ctl00$ContentPlaceHolder3$hffilterclick") != null)
                    {
                        HiddenField hf = (HiddenField)frmObj.FindControl("ctl00$ContentPlaceHolder3$hffilterclick");
                        if (hf != null)
                        {
                            if (hf.Value == "1")
                            {
                                objGG.BuildQuickSearch(dtaPage, dtaPageSrch, strPagesetRowID, frmObj); // Commented by srivatsan on July 27 2009
                            }
                        }
                    }

                }
                else
                {
                    if (HttpContext.Current.Request.QueryString["flmode"] != null)
                    {
                        if (HttpContext.Current.Request.QueryString["flmode"] == "1")
                        {
                            HiddenField hf = (HiddenField)frmObj.FindControl("ctl00$ContentPlaceHolder3$hffilterclick");
                            if (hf != null) hf.Value = "1";
                            objGG.BuildQuickSearch(dtaPage, dtaPageSrch, strPagesetRowID, frmObj);

                        }
                    }
                }
                //if (frmObj.FindControl("ctl00$ContentPlaceHolder3$hihDeleteClick") != null)
                //{
                //    HtmlInputHidden hiddfield = (HtmlInputHidden)frmObj.FindControl("ctl00$ContentPlaceHolder3$hihDeleteClick");
                //    if (hiddfield.Value == "1")
                //    {
                //        if (HttpContext.Current.Request.QueryString["PK"] == null)
                //        {
                //            objGG.BuildQuickSearch(dtaPage, dtaPageSrch, strPagesetRowID, frmObj);
                //        }
                //    }
                //}

            }
           return blnStatus; // Added by 'Imran Gani' on 24-Sep-2014, to avoid server code of loading records after filter load
            Hashtable hsDatatype = new Hashtable();
            string sFieldAlias = "";

            string sQuickSearch = "";
            if (frmObj.Page.IsPostBack)
            {
                sQuickSearch = objGG.PagesetObjectSearchSql(ref dtaPageSrch, ref dtaPageControls, ref dtaPage, frmObj, ref HDD); //Changes Made By Dhanapal On Dec 15 2010 For Search All Fields
                if (sQuickSearch == "")
                    sQuickSearch = objGG.PagesetQuickSearchSql(dtaPageSrch, frmObj);

            }
            else
            {
                if (HttpContext.Current.Request.QueryString["flmode"] != null)
                {
                    if (HttpContext.Current.Request.QueryString["flmode"] == "1")
                    {
                        sQuickSearch = objGG.PagesetQuickSearchSql(dtaPageSrch, frmObj);
                    }
                }
            }
            bool bIsCombinedOrderBy = false;//for case 00008760,00008761
            string sCombinedOrderBy = "";//for case 00008760,00008761
            string Order = " desc";
            string sOrderby = getSortField(dtaPageControls, ref Order);
            string strSql = PageSetSelectSql(dtaPage, dtaPageKeys, dtaPageSrch, ref dtaPageControls, ref hsDatatype, "", ref sFieldAlias, frmObj, sQuickSearch, ref bIsCombinedOrderBy, sOrderby, ref sCombinedOrderBy, Order);
            //if (bIsCombinedOrderBy)
            //{
            //    if (Order.Trim() == "asc")
            //        sOrderby = sCombinedOrderBy + " desc " + sOrderby + " desc ";
            //    else
            //        sOrderby = sCombinedOrderBy + " asc " + sOrderby + " asc ";
            //}
            if (strSql != "")
            {
                #region Old Lines commented by 'Imran Gani' on 14-Mar-2014, to avoid top key from query and use ROW_NUMBER().
                //if (frmObj.Page.IsPostBack)
                //{
                //    if (sQuickSearch == "")
                //        strSql += objGG.PagesetQuickSearchSql(dtaPageSrch, frmObj);
                //}
                //if (sQuickSearch != "") // Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security
                //{
                //    strSql += sQuickSearch;
                //    //strSql = strSql.Replace("or owner_id is null", ""); // Line commented by 'Imran Gani' on 28-Jun-2013, to handle Org security with owner_id has null value.
                //}
                ////strSql += HDS.GridRowLevelSecuritySql(dtaPage);
                ////strSql += sQuickSearch; // commented by 'Imran Gani' on 05-June-2013 for Org Security
                ////string strModifiedFields = objGG.GetModifiedFields(ref dtaPage, ref dtaPageControls);
                ////if (strModifiedFields != "") strSql = strSql.TrimEnd() + " order by " + strModifiedFields;

                //if (Order.Trim() == "asc")
                //{
                //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " desc" + " ,[keys] desc ";
                //}
                //else
                //{
                //    strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " asc" + " ,[keys] desc ";
                //}
                //strSql = "Select top " + GlobalValues.intNoOfRecordsPerPage.ToString() + " " + sFieldAlias + " from ( " + strSql + ") as tt order by " + sOrderby + " " + Order + " ,[keys] asc ";

                ////if (bIsCombinedOrderBy)//for case 00008760,00008761 //Commented on Feb 26 2010
                ////{
                ////    if (Order.Trim() == "asc")
                ////    {
                ////        strSql = strSql.TrimEnd() + " order by " + sCombinedOrderBy + " desc, " + sOrderby + " desc ";
                ////    }
                ////    else
                ////    {
                ////        strSql = strSql.TrimEnd() + " order by " + sCombinedOrderBy + " desc, " + sOrderby + " asc ";
                ////    }
                ////}
                ////else
                ////{
                ////    if (Order.Trim() == "asc")
                ////    {
                ////        strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " desc";
                ////    }
                ////    else
                ////    {
                ////        strSql = strSql.TrimEnd() + " order by " + sOrderby + " " + " asc";
                ////    }
                ////}

                ////if (bIsCombinedOrderBy)
                ////{
                ////    strSql = "Select top " + GlobalValues.intNoOfRecordsPerPage.ToString() + " " + sFieldAlias + " from ( " + strSql + ") as tt order by " + sCombinedOrderBy + " asc" /*+ Order*/ + " , " + sOrderby + " " + Order;
                ////}
                ////else
                ////{
                ////    strSql = "Select top " + GlobalValues.intNoOfRecordsPerPage.ToString() + " " + sFieldAlias + " from ( " + strSql + ") as tt order by " + sOrderby + " " + Order;
                ////}
                #endregion

                DataSet dseObj = HDD.GetDataset(strSql);

                if (dseObj.Tables.Count == 0)
                    return false;
                else
                {
                    FillBindAndMasterRelatedValues(dseObj, dtaPage, dtaPageSrch, dtaPageKeys); // Added by 'Imran Gani' on 11-Mar-2013,

                    #region Old coding to load Bind and Master Values, Command by 'Imran Gani' on 11-Mar-2013

                    /* Command by 'Imran Gani' on 11-Mar-2013, to call fillBindAndMasterRelatedValues function
                    
                    for (int i = 0; i < dtaPage.Rows.Count; i++) //added by Prithi on 13 Oct 2008 to display the display field instead of storage field in place of af_row_id.
                    {
                        string strPageId, strSearchAttribName, strBindRowID;
                        strPageId = dtaPage.Rows[i]["page_id"].ToString();
                        DataRow[] droPageSrch = dtaPageSrch.Select("page_id='" + strPageId.Replace("'", "''") + "' and list_flag=1", "search_seq");
                        for (int j = 0; j < droPageSrch.Length; j++)
                        {
                            strSearchAttribName = droPageSrch[j]["search_attrib_name"].ToString();
                            if (strSearchAttribName == "")
                            {
                                strSearchAttribName = droPageSrch[j]["search_attrib_id"].ToString();
                            }

                            if (droPageSrch[j]["search_attrib_id"].ToString() == "created_by" || droPageSrch[j]["search_attrib_id"].ToString() == "modified_by" || droPageSrch[j]["search_attrib_id"].ToString() == "owner_id") // Added by srivatsan on June 15 2009 for owner id field
                            {
                                string sUserDisplayName = objGG.getUserDisplayName();
                                DataTable dtUser = HDD.GetDataTable("select *, " + sUserDisplayName + " as display_name from sy_usr");
                                string sUser_afrowid = "";
                                string sUser = "";
                                foreach (DataRow dr in dseObj.Tables[0].Rows)
                                {
                                    if (sUser_afrowid != dr[strSearchAttribName].ToString())
                                    {
                                        sUser_afrowid = dr[strSearchAttribName].ToString();
                                        DataRow[] drr = dtUser.Select("af_row_id='" + sUser_afrowid + "'");
                                        if (drr.Length > 0)
                                            sUser = drr[0]["display_name"].ToString();//sUser = drr[0]["user_id"].ToString();
                                        drr = null;
                                    }
                                    dr[strSearchAttribName] = sUser;
                                }
                                dtUser.Dispose();
                                dtUser = null;
                            }

                            strBindRowID = droPageSrch[j]["control_bind_id"].ToString();
                            if (strBindRowID != "")
                            {
                                string search_attrib_name = droPageSrch[j]["search_attrib_name"].ToString();
                                string sBindStoreField = "", sBindDisplayField = "", sBindTable = "";
                                DataRow drBind = null;
                                if (strBindRowID != "") drBind = HDD.GetTableRow("select * from sy_bnd where af_row_id = '" + strBindRowID + "';");
                                if (drBind != null)
                                {
                                    sBindStoreField = drBind["bind_value"].ToString();
                                    sBindDisplayField = drBind["bind_text"].ToString();
                                    sBindTable = drBind["bind_table"].ToString();
                                    //if (sBindStoreField.ToLower() == "af_row_id") // Commented by srivatsan on July 15 2009
                                    //{
                                    //    string sSql = "";
                                    //    DataTable dt = new DataTable();
                                    //    sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable + "";
                                    //    dt = HDD.GetDataTable(sSql, sBindTable);
                                    //    foreach (DataRow dr in dseObj.Tables[0].Rows)
                                    //    {
                                    //        if (dr[strSearchAttribName].ToString() == "") dr[strSearchAttribName] = "";
                                    //        else
                                    //        {
                                    //            DataRow[] drr = dt.Select("af_row_id= '" + dr[strSearchAttribName].ToString() + "'");
                                    //            if (drr.Length == 0) dr[strSearchAttribName] = "Record Not Found";
                                    //            else
                                    //            {
                                    //                for (int l = 0; l < drr.Length; l++)
                                    //                {
                                    //                    dr[strSearchAttribName] = drr[l][sBindDisplayField].ToString();
                                    //                }
                                    //            }
                                    //        }
                                    //    }
                                    //    dt.Dispose();
                                    //    dt = null;
                                    //}


                                    // Modified by srivatsan on July 15 2009
                                    addBindColumn(dseObj, search_attrib_name);

                                    string af_row_ids = "";
                                    if (dseObj != null)
                                    {
                                        if (dseObj.Tables.Count > 0)
                                        {
                                            if (dseObj.Tables[0].Rows.Count > 0)
                                            {
                                                af_row_ids = getDistinct(dseObj.Tables[0], search_attrib_name);
                                            }
                                        }
                                    }
                                    string sSql = "";
                                    DataTable dt = new DataTable();
                                    if (af_row_ids != "")
                                    {
                                        sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable + " where " + sBindStoreField + " in (" + af_row_ids + ")";
                                    }
                                    else
                                    {
                                        sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable;
                                    }
                                    dt = HDD.GetDataTable(sSql, sBindTable);
                                    foreach (DataRow dr in dseObj.Tables[0].Rows)
                                    {
                                        if (dr[strSearchAttribName].ToString() == "") dr[strSearchAttribName] = "";
                                        else
                                        {
                                            DataRow[] drr = dt.Select("" + sBindStoreField + "= '" + dr[strSearchAttribName].ToString().Replace("'", "''") + "'");
                                            if (drr.Length == 0) dr[strSearchAttribName] = "Record Not Found";
                                            else
                                            {
                                                for (int l = 0; l < drr.Length; l++)
                                                {
                                                    if (!sBindDisplayField.Contains("+"))
                                                    {
                                                        dr[strSearchAttribName] = drr[l][sBindDisplayField].ToString();
                                                    }
                                                    else
                                                    {
                                                        try
                                                        {
                                                            dr[strSearchAttribName] = drr[l]["Column1"].ToString();
                                                        }
                                                        catch { dr[strSearchAttribName] = ""; }

                                                    }
                                                }
                                            }
                                        }
                                    }
                                    dt.Dispose();
                                    dt = null;

                                }
                            }
                        }
                    }

                    dseObj.Tables[0].TableName = dtaPage.Rows[0]["page_id"].ToString();
                    //objGG.sortData(ref dseObj);
                    if (dtaPageKeys.Rows.Count > 0)
                        objGG.populateMasterFieldValues(ref dseObj, ref dtaPageSrch, ref dtaPageKeys);
                    //dseObj = sortData(dseObj, "modified_at");
                    
                    Command by 'Imran Gani' on 11-Mar-2013, to call fillBindAndMasterRelatedValues function*/
                    #endregion

                    objGG.BuildGrid(dseObj, strPagesetRowID, frmObj, bCreate, bEdit, bDelete, ref dsePageObj, ref hsDatatype);
                }
            }
            HDS.displayHelp(dtaPage, DDI.FindControl(frmObj.Controls, "imgHelp"));


            if ((HttpContext.Current.Request.QueryString["PK"] == null) && (HDS.allRightsForNGMODEL() == false))
            {
                objGG.showadditionalsections(strPagesetRowID, ref frmObj, dsePageObj);
            }

        }
        HtmlInputButton btnObj = (HtmlInputButton)DDI.FindControl(frmObj.Controls, "btnAddNew");  // Modified by srivatsan
        if (btnObj != null)
            if (bCreate.ToString() == false.ToString())
                objGG.makeAddButtonInvisible(frmObj, btnObj);
        if (btnObj != null)
            if (!HDS.getRightsForPagesetObjects(strPagesetRowID, "create", true))
                objGG.makeAddButtonInvisible(frmObj, btnObj);
        objGG = null;
        HDD = null;
        HDS = null;
        DDI = null;
        return blnStatus;
    }

    /// <summary>
    /// To replace the bind data and master records values.
    /// </summary>
    /// <param name="dseObj">Data table of display records</param>
    /// <param name="dtaPage">page details</param>
    /// <param name="dtaPageSrch">page search</param>
    /// <param name="dtaPageKeys">page key</param> // Implemented by 'Imran Gani' on 11-Mar-2013.
    public void FillBindAndMasterRelatedValues(DataSet dseObj, DataTable dtaPage, DataTable dtaPageSrch, DataTable dtaPageKeys)
    {
        GenerateGrid objGG = new GenerateGrid();
        HDDatabase HDD = new HDDatabase();
        for (int i = 0; i < dtaPage.Rows.Count; i++) //added by Prithi on 13 Oct 2008 to display the display field instead of storage field in place of af_row_id.
        {
            string strPageId, strSearchAttribName, strBindRowID;
            strPageId = dtaPage.Rows[i]["page_id"].ToString();
            DataRow[] droPageSrch = dtaPageSrch.Select("page_id='" + strPageId.Replace("'", "''") + "' and list_flag=1", "search_seq");
            for (int j = 0; j < droPageSrch.Length; j++)
            {
                strSearchAttribName = droPageSrch[j]["search_attrib_name"].ToString();
                if (strSearchAttribName == "")
                    strSearchAttribName = droPageSrch[j]["search_attrib_id"].ToString();

                if (droPageSrch[j]["search_attrib_id"].ToString() == "created_by" || droPageSrch[j]["search_attrib_id"].ToString() == "modified_by" || droPageSrch[j]["search_attrib_id"].ToString() == "owner_id") // Added by srivatsan on June 15 2009 for owner id field
                {
                    string sUserDisplayName = objGG.getUserDisplayName();
                    DataTable dtUser = HDD.GetDataTable("select *, " + sUserDisplayName + " as display_name from sy_usr");
                    string sUser_afrowid = "";
                    string sUser = "";
                    foreach (DataRow dr in dseObj.Tables[0].Rows)
                    {
                        if (sUser_afrowid != dr[strSearchAttribName].ToString())
                        {
                            sUser_afrowid = dr[strSearchAttribName].ToString();
                            DataRow[] drr = dtUser.Select("af_row_id='" + sUser_afrowid + "'");
                            if (drr.Length > 0)
                                sUser = drr[0]["display_name"].ToString();//sUser = drr[0]["user_id"].ToString();
                            drr = null;
                        }
                        dr[strSearchAttribName] = sUser;
                    }
                    dtUser.Dispose();
                    dtUser = null;
                }

                strBindRowID = droPageSrch[j]["control_bind_id"].ToString();
                if (strBindRowID != "")
                {
                    string search_attrib_name = droPageSrch[j]["search_attrib_name"].ToString();
                    string sBindStoreField = "", sBindDisplayField = "", sBindTable = "";
                    DataRow drBind = null;
                    if (strBindRowID != "") drBind = HDD.GetTableRow("select * from sy_bnd where af_row_id = '" + strBindRowID + "';");
                    if (drBind != null)
                    {
                        sBindStoreField = drBind["bind_value"].ToString();
                        sBindDisplayField = drBind["bind_text"].ToString();
                        sBindTable = drBind["bind_table"].ToString();
                        //if (sBindStoreField.ToLower() == "af_row_id") // Commented by srivatsan on July 15 2009
                        //{
                        //    string sSql = "";
                        //    DataTable dt = new DataTable();
                        //    sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable + "";
                        //    dt = HDD.GetDataTable(sSql, sBindTable);
                        //    foreach (DataRow dr in dseObj.Tables[0].Rows)
                        //    {
                        //        if (dr[strSearchAttribName].ToString() == "") dr[strSearchAttribName] = "";
                        //        else
                        //        {
                        //            DataRow[] drr = dt.Select("af_row_id= '" + dr[strSearchAttribName].ToString() + "'");
                        //            if (drr.Length == 0) dr[strSearchAttribName] = "Record Not Found";
                        //            else
                        //            {
                        //                for (int l = 0; l < drr.Length; l++)
                        //                {
                        //                    dr[strSearchAttribName] = drr[l][sBindDisplayField].ToString();
                        //                }
                        //            }
                        //        }
                        //    }
                        //    dt.Dispose();
                        //    dt = null;
                        //}


                        // Modified by srivatsan on July 15 2009
                        addBindColumn(dseObj, search_attrib_name);

                        string af_row_ids = "";
                        if (dseObj != null)
                        {
                            if (dseObj.Tables.Count > 0)
                            {
                                if (dseObj.Tables[0].Rows.Count > 0)
                                {
                                    af_row_ids = getDistinct(dseObj.Tables[0], search_attrib_name);
                                }
                            }
                        }
                        string sSql = "";
                        DataTable dt = new DataTable();
                        if (af_row_ids != "")
                            sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable + " where " + sBindStoreField + " in (" + af_row_ids + ")";
                        else
                            sSql = "select " + sBindDisplayField + "," + sBindStoreField + " from " + sBindTable;
                        
                        dt = HDD.GetDataTable(sSql, sBindTable);
                        foreach (DataRow dr in dseObj.Tables[0].Rows)
                        {
                            if (dr[strSearchAttribName].ToString() == "") dr[strSearchAttribName] = "";
                            else
                            {
                                DataRow[] drr = dt.Select("" + sBindStoreField + "= '" + dr[strSearchAttribName].ToString().Replace("'", "''") + "'");
                                if (drr.Length == 0) dr[strSearchAttribName] = "Record Not Found";
                                else
                                {
                                    for (int l = 0; l < drr.Length; l++)
                                    {
                                        if (!sBindDisplayField.Contains("+"))
                                            dr[strSearchAttribName] = drr[l][sBindDisplayField].ToString();
                                        else
                                        {
                                            try
                                            {
                                                dr[strSearchAttribName] = drr[l]["Column1"].ToString();
                                            }
                                            catch { dr[strSearchAttribName] = ""; }
                                        }
                                    }
                                }
                            }
                        }
                        dt.Dispose();
                        dt = null;
                    }
                }
            }
        }

        dseObj.Tables[0].TableName = dtaPage.Rows[0]["page_id"].ToString();
        if (dtaPageKeys.Rows.Count > 0)
            objGG.populateMasterFieldValues(ref dseObj, ref dtaPageSrch, ref dtaPageKeys);
    }

    public string PageSetSelectSql(DataTable dtaPage, DataTable dtaPageKeys, DataTable dtaPageSrch, ref DataTable dtPageControls, ref Hashtable hsDatatype, string childField, ref string FieldAliases, HtmlForm frmObj, string QuickSearchSQL, ref bool IsCombinedOrderBy, string OrderBy, ref string CombinedOrderBy, string SortOrder)
    {
        string strPageSql = "";
        try
        {
            GenerateGrid objGG = new GenerateGrid();
            string strTableNames = objGG.GetTableNames(dtaPage, dtaPageSrch);

            if (strTableNames != "")
            {
                SecurityFilter objSec = new SecurityFilter();
                string sAFAdmin = objSec.QueryForAFAdmin();
                //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                HDDatabase HDD = new HDDatabase();
                string modelConString = "";
                modelConString = HttpContext.Current.Session["servercon"].ToString();
                string str_OwnerId = "";
                string str_BusinessUnit = "";
                if (HttpContext.Current.Session["dbcon"].ToString() != modelConString && sAFAdmin != "")
                {
                    BusinessUnit.Access ACS = new BusinessUnit.Access(HttpContext.Current.Session["userid"].ToString(), HDD.GetConnection().ConnectionString, dtaPage.Rows[0]["page_id"].ToString());
                    str_OwnerId = ACS.AccessableOwners;
                    str_BusinessUnit = ACS.AccessableBuUnits;
                }
                string sCustodianFilter = ""; //= objSec.QueryForCustodianFilter();
                //----------------End for Org Security------------------
                if (sCustodianFilter.Trim() != "")
                    if (!sCustodianFilter.StartsWith("or"))
                    {
                        if (sAFAdmin.Trim() != "")
                        {
                            sAFAdmin = "(" + sAFAdmin + " and " + sCustodianFilter + ") ";
                        }
                        else
                        {
                            sAFAdmin = "(" + sCustodianFilter + ") ";
                        }
                    }
                    else
                    {
                        //if (QuickSearchSQL.Trim() == "")  // if no search exists show all no owner records
                        //{
                        if (sAFAdmin.Trim() != "")
                        {
                            sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                        }
                        else
                        {
                            sAFAdmin = "(" + sCustodianFilter + ") ";
                        }
                        //sAFAdmin += " " + sCustodianFilter;
                        // }
                    }
                objSec = null;
                //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                string str_Filter = sAFAdmin;
                TextBox txtObjectSearch = (TextBox)frmObj.FindControl("ctl00$ContentPlaceHolder3$txtObjectSearch");
                if (QuickSearchSQL == "" || (txtObjectSearch != null && txtObjectSearch.Text != "")) // Added by 'Imran Gani' on 28-Jun-2013, to include org security when search text is there - not for filter.
                {
                    if (str_OwnerId != "" && dtPageControls.Select("control_id='owner_id' or control_attrib_id='owner_id'").Length > 0)
                    {
                        if (sAFAdmin != "")
                            str_Filter += str_OwnerId;
                        else
                            str_Filter += " " + str_OwnerId.Remove(0, 5) + " ";
                    }
                    str_Filter += (str_Filter == "" ? "" : " or owner_id is null ");
                    if (str_BusinessUnit != "" && dtPageControls.Select("control_id='bu_id' or control_attrib_id='bu_id'").Length > 0)
                    {
                        if (sAFAdmin != "")
                            str_Filter += str_BusinessUnit;
                        else
                            str_Filter += " " + str_BusinessUnit + " ";
                    }
                }
                string iTotalRecords = getTotalRecordsToFetch(strTableNames, str_Filter, QuickSearchSQL, frmObj, ref IsCombinedOrderBy, OrderBy);
                //string iTotalRecords = getTotalRecordsToFetch(strTableNames, sAFAdmin, QuickSearchSQL, frmObj, ref IsCombinedOrderBy, OrderBy);
                //----------------End for Org Security------------------
                string strSelectFlds = objGG.GetSelectFlds(dtaPage, dtaPageSrch, ref hsDatatype, ref FieldAliases, ref dtPageControls, ref CombinedOrderBy, ref OrderBy);
                if (strSelectFlds != "")
                {
                    FieldAliases = "[keys], " + FieldAliases;
                    string strKeyValues = objGG.GetKeyValues(dtaPage, dtaPageSrch, dtaPageKeys);
                    string strJoins = objGG.GetJoins(dtaPage, dtaPageSrch, dtaPageKeys);
                    
                    #region Added by 'Imran Gani' on 14-Mar-2014, to use ROW_NUMBER() in query and also to include the search parameter.
                    if (strKeyValues != "")
                        strPageSql = "select " + strKeyValues + " keys, " + strSelectFlds + ", ROW_NUMBER() OVER (ORDER BY " + OrderBy + " " + SortOrder + ", " + strKeyValues + " asc) AS [row] from " + strTableNames;
                    else
                        strPageSql = "select " + strSelectFlds + ", ROW_NUMBER() OVER (ORDER BY " + OrderBy + " " + SortOrder + ") AS [row] from " + strTableNames;

                    if (childField.Length > 0)
                        if (HttpContext.Current.Request["PK"] != null)
                            strJoins += childField + "='" + HttpContext.Current.Request["PK"].ToString() + "'";

                    if (dtaPage != null && dtaPage.Rows[0]["page_id"].ToString() == "p_sy_report") // Added by 'Imran Gani' on 25-Jan-2013, for report security per role.
                    {
                        if (str_Filter != "")
                            strPageSql += " where (" + str_Filter + " or [" + dtaPage.Rows[0]["page_id"].ToString() + "].[af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 ))";
                        else
                            strPageSql += " where 1=1 ";
                    }
                    else
                    {
                        if (str_Filter != "")
                            strPageSql += " where (" + str_Filter + ")";
                        else if (strJoins != "")
                            strPageSql += " where " + strJoins;
                        else
                            strPageSql += " where 1=1 ";
                    }
                    if (frmObj.Page.IsPostBack)
                        if (QuickSearchSQL == "")
                            strPageSql += objGG.PagesetQuickSearchSql(dtaPageSrch, frmObj);
                    if (QuickSearchSQL != "")
                        strPageSql += QuickSearchSQL;

                    int iCurrentPage = getCurrentPage(frmObj.Controls);
                    int iStartCount = 0;
                    if (iCurrentPage > 1)
                        iStartCount = ((iCurrentPage - 1) * GlobalValues.intNoOfRecordsPerPage);
                    int iEndCount = iStartCount + GlobalValues.intNoOfRecordsPerPage;
                    iStartCount++;
                    strPageSql = "select " + FieldAliases + " from (" + strPageSql + ") as tt where [row] between " + iStartCount + " and " + iEndCount + " ";
                    #endregion

                    #region Old Lines commented by 'Imran Gani' on 14-Mar-2014, to avoid top key from query and use ROW_NUMBER().
                    //if (strKeyValues != "")
                    //    strPageSql = "select top " + iTotalRecords.ToString() + " " + strKeyValues + " keys, " + strSelectFlds + " from " + strTableNames + "";
                    //else
                    //    strPageSql = "select " + strSelectFlds + " from " + strTableNames + "";

                    //if (childField.Length > 0)
                    //    if (HttpContext.Current.Request["PK"] != null)
                    //        strJoins += childField + "='" + HttpContext.Current.Request["PK"].ToString() + "'";

                    //if (dtaPage != null && dtaPage.Rows[0]["page_id"].ToString() == "p_sy_report") // Added by 'Imran Gani' on 25-Jan-2013, for report security per role.
                    //{
                    //    //if (sAFAdmin != "") // Lines commented by 'Imran Gani' on 28-Jun-2013, to handle Org security for report with report access.
                    //    //    strPageSql += " where (" + sAFAdmin + " and owner_id = '" + HttpContext.Current.Session["user_afrowid"] + "' or owner_id is null or [" + dtaPage.Rows[0]["page_id"].ToString() + "].[af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 ))";
                    //    if (str_Filter != "") // Added by 'Imran Gani' on 28-Jun-2013, to handle Org security for report with report access.

                    //        strPageSql += " where (" + str_Filter + " or [" + dtaPage.Rows[0]["page_id"].ToString() + "].[af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 ))";
                    //    else
                    //        strPageSql += " where 1=1 ";
                    //}
                    //else
                    //{
                    //    //if (sAFAdmin != "" && QuickSearchSQL == "") // Lines commented by 'Imran Gani' on 28-Jun-2013, to handle Org security for records.
                    //    //{
                    //    //    strPageSql += " where " + sAFAdmin;
                    //    //}
                    //    if (str_Filter != "")  // Added by 'Imran Gani' on 28-Jun-2013, to handle Org security for records.
                    //        strPageSql += " where (" + str_Filter + ")";
                    //    else if (strJoins != "")
                    //    {
                    //        strPageSql += " where " + strJoins;
                    //    }
                    //    else
                    //    {
                    //        strPageSql += " where 1=1 ";
                    //    }
                    //    // Lines commented by 'Imran Gani' on 28-Jun-2013, to handle Org security for records.
                    //    //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                    //    //if (QuickSearchSQL == "") // Added by 'Imran Gani' on 27-Jun-2013, to avoid org security when search text is there.
                    //    //{
                    //    //    if (str_OwnerId != "" && dtPageControls.Select("control_id='owner_id' or control_attrib_id='owner_id'").Length > 0)
                    //    //    {
                    //    //        if (strPageSql.Contains(" where "))
                    //    //            strPageSql += str_OwnerId + " or owner_id is null ";
                    //    //        else
                    //    //            strPageSql += " where " + str_OwnerId.Remove(0, 5) + " or owner_id is null ";
                    //    //    }
                    //    //    if (str_BusinessUnit != "" && dtPageControls.Select("control_id='bu_id' or control_attrib_id='bu_id'").Length > 0)
                    //    //    {
                    //    //        if (strPageSql.Contains(" where "))
                    //    //            strPageSql += str_BusinessUnit;
                    //    //        else
                    //    //            strPageSql += " where " + str_BusinessUnit.Remove(0, 5);
                    //    //    }
                    //    //}
                    //    //----------------End for Org Security------------------
                    //}
                    #endregion
                }
            }
        }

        catch
        {
        }
        return strPageSql;
    }

    private string getTotalRecordsToFetch(string TableName, string Filter, string QuickSearch, HtmlForm frmObj, ref bool IsCombinedOrderBy, string OrderBy)
    {
        int iTotalRecords = 0;
        try
        {
            int iRecordCount = 0;
            //-----------Lines Added by 'Imran Gani' on 28-Jun-2013, to handle Org security for records.---------//
            string sFilter = (Filter.Trim() == "" ? "" : "(" + Filter + ")") + QuickSearch;
            TextBox txtObjectSearch = (TextBox)frmObj.FindControl("ctl00$ContentPlaceHolder3$txtObjectSearch");
            if (QuickSearch != "" && (txtObjectSearch == null || txtObjectSearch.Text == "")) sFilter = QuickSearch;
            if (sFilter.Trim().StartsWith("and"))
                sFilter = sFilter.Remove(0, " and ".Length);
            //-----------End of handling Org security for records.---------//
            string sSQL = "";
            string sDataSort = "";
            if (HttpContext.Current.Session["datasort"] != null)
            {
                sDataSort = HttpContext.Current.Session["datasort"].ToString();
            }
            if (sDataSort.Trim() != "")
            {
                if (sFilter.Trim() != "")
                    sSQL = "select count(*) from " + TableName + " where " + sFilter;
                else
                    sSQL = "select count(*) from " + TableName;
            }
            else //for case 00008760,00008761
            {
                if (sFilter.Trim() != "")
                {
                    if (HttpContext.Current.Request["pgs_id"] != null && HttpContext.Current.Request["pgs_id"].ToString() == "6421de320e189de8") // Added by 'Imran Gani' on 25-Jan-2013, for report security per role.
                        sSQL = "select count(*) from " + TableName + " where (" + sFilter + " or [af_row_id] in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and [is_accessible]=1 )) " + QuickSearch + ";";
                    else
                        sSQL = "select count(*) from " + TableName + " where " + sFilter + ";";
                    sSQL = sSQL + "select distinct(" + OrderBy + ") from " + TableName + " where " + sFilter + ";";
                }
                else
                {
                    sSQL = "select count(*) from " + TableName + ";";
                    sSQL = sSQL + "select distinct(" + OrderBy + ") from " + TableName + ";";
                }
            }
            HDDatabase HDD = new HDDatabase();
            DataSet dsTemp = HDD.GetDataset(sSQL);//for case 00008760,00008761
            HDD = null;
            if (dsTemp.Tables.Count > 0)
            {
                string sTotalRecords = "0";
                if (dsTemp.Tables[0].Rows.Count > 0)
                {
                    sTotalRecords = dsTemp.Tables[0].Rows[0][0].ToString();
                }
                DynamicDisplayI DDI = new DynamicDisplayI();
                HtmlInputHidden hihObj = (HtmlInputHidden)DDI.FindControl(frmObj.Controls, "hihTotalRecordCount");
                DDI = null;
                if (hihObj != null)
                {
                    //HDDatabase HDD = new HDDatabase();
                    hihObj.Value = sTotalRecords;
                    //HDD = null;
                    iRecordCount = int.Parse(hihObj.Value);
                }
            }

            //setTotalNumberofRecords(sSQL, frmObj, ref iRecordCount);
            int iRemaining = 0;

            int iTotalPages = getTotalPages(frmObj.Controls, ref iRemaining);

            if (dsTemp.Tables.Count > 1)
            {
                if (dsTemp.Tables[1].Rows.Count < iTotalPages)
                {
                    IsCombinedOrderBy = true;
                }
            }

            dsTemp.Dispose();
            dsTemp = null;

            int iCurrPage = getCurrentPage(frmObj.Controls);

            CompareCurrPageValue(ref iTotalPages, ref iCurrPage, frmObj); // Added bysrivatsan to fix deleting in list when the last page has only one record.

            if (iCurrPage == iTotalPages)
            {
                if (iRemaining == 0)
                {
                    iTotalRecords = GlobalValues.intNoOfRecordsPerPage;
                }
                else
                {
                    iTotalRecords = iRemaining;
                }
            }
            else if (iCurrPage == 1)
            {
                iTotalRecords = iRecordCount;
            }
            else
            {
                iTotalRecords = iRecordCount - (iCurrPage * GlobalValues.intNoOfRecordsPerPage);
                iTotalRecords = ((iTotalPages - iCurrPage) * GlobalValues.intNoOfRecordsPerPage) + iRemaining;
            }
        }

        catch
        {
        }
        return iTotalRecords.ToString();
    }

    private void setTotalNumberofRecords(string SQL, HtmlForm frmObj, ref int iTotalRecords)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        HtmlInputHidden hihObj = (HtmlInputHidden)DDI.FindControl(frmObj.Controls, "hihTotalRecordCount");
        DDI = null;
        if (hihObj != null)
        {
            HDDatabase HDD = new HDDatabase();
            hihObj.Value = HDD.GetColumnValue(SQL).ToString();
            HDD = null;
            iTotalRecords = int.Parse(hihObj.Value);
        }
    }

    private int getTotalPages(ControlCollection frmObj, ref int RemainingRecords)
    {
        int intTotalPages = 1;
        DynamicDisplayI DDI = new DynamicDisplayI();
        HtmlInputHidden hihObj = (HtmlInputHidden)DDI.FindControl(frmObj, "hihTotalRecordCount");
        DDI = null;
        if (hihObj != null)
        {
            intTotalPages = Convert.ToInt32(hihObj.Value) / GlobalValues.intNoOfRecordsPerPage;
            if (Convert.ToInt32(hihObj.Value) % GlobalValues.intNoOfRecordsPerPage > 0)
            {
                intTotalPages = intTotalPages + 1;
                RemainingRecords = Convert.ToInt32(hihObj.Value) % GlobalValues.intNoOfRecordsPerPage;
            }
        }
        return intTotalPages;
    }

    private int getCurrentPage(ControlCollection frmObj)
    {
        int intCurrentPage = 1;
        DynamicDisplayI DDI = new DynamicDisplayI();
        HtmlInputHidden hihObj = (HtmlInputHidden)DDI.FindControl(frmObj, "hihCurrentPageId");
        DDI = null;
        if (hihObj != null)
        {
            intCurrentPage = Convert.ToInt32(hihObj.Value);
        }
        return intCurrentPage;
    }

    public string getSortField(DataTable dtPageControls, ref string Order)
    {
        string sOrderby = "modified_at";
        if (HttpContext.Current.Session["datasort"] != null)
        {
            string datasort = HttpContext.Current.Session["datasort"].ToString();
            if (datasort.Trim() != "")
            {
                string[] array = datasort.Split(' ');
                string content = "";
                string colName = "";
                //string tableName = "";
                content = datasort;
                //tableName = getTableName(content);
                colName = getColName(content);
                datasort = content.Substring(content.LastIndexOf("]") + 1).Replace("]", "");
                sOrderby = "[" + colName + "]";
                Order = datasort;
            }
            else
            {
                if (dtPageControls.Select("control_attrib_id='modified_at'").Length > 0)
                    sOrderby = "modified_at";
                else
                    if (dtPageControls.Select("control_attrib_id='modified_date'").Length > 0)
                        sOrderby = "modified_date";
            }
        }
        else
        {
            if (dtPageControls.Select("control_attrib_id='modified_at'").Length > 0)
                sOrderby = "modified_at";
            else
                if (dtPageControls.Select("control_attrib_id='modified_date'").Length > 0)
                    sOrderby = "modified_date";
        }

        return sOrderby;
    }

    private string getTableName(string content)
    {
        try
        {
            string tableName = "";
            tableName = content.Substring(0, content.IndexOf("].["));
            tableName = tableName.Trim('[').Trim(']');
            return tableName;
        }
        catch
        {
            return "";
        }
    }

    private string getColName(string content)
    {
        try
        {
            string colName = "";
            colName = content.Substring(content.IndexOf("].[") + 3);
            colName = colName.Substring(0, colName.IndexOf("]"));
            return colName;
        }
        catch
        {
            return "";
        }
    }

    public string getDistinct(DataTable dt, string field) // Get distinct values from the datatable for the field as string
    {
        StringBuilder sb = new StringBuilder();
        string result = "";
        try
        {
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr[field].ToString() != "")
                    {
                        if (!sb.ToString().Contains("'" + dr[field].ToString() + "'"))
                        {
                            sb.Append("'" + dr[field].ToString().Replace("'", "''") + "',");
                        }
                    }
                }
                if (sb.ToString() != "")
                {
                    result = sb.ToString().Substring(0, sb.Length - 1);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetDistinctRecords :" + ex.Message);
        }
        return result;

    }

    // This will create a temp column for bind with string datatype and remove existing column.
    // Used for displaying bind fields in list page
    public DataSet addBindColumn(DataSet ds, string bindcolumn)  // Added by srivatsan on July 16 2009
    {
        int ordinalposition = 0;
        if (ds != null)
        {
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Columns.Contains(bindcolumn))
                    {
                        ds.Tables[0].Columns.Add(bindcolumn + "_temp");

                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            ds.Tables[0].Rows[i][bindcolumn + "_temp"] = ds.Tables[0].Rows[i][bindcolumn];
                        }

                        ordinalposition = ds.Tables[0].Columns[bindcolumn].Ordinal;
                        ds.Tables[0].Columns.Remove(bindcolumn);

                        // foreach (DataColumn dc in ds.Tables[0].Columns)
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                        {
                            if (ds.Tables[0].Columns[j].Caption == bindcolumn + "_temp")
                            {
                                ds.Tables[0].Columns[j].Caption = bindcolumn;
                                ds.Tables[0].Columns[j].ColumnName = bindcolumn;
                                ds.Tables[0].Columns[j].SetOrdinal(ordinalposition);

                                ds.AcceptChanges();

                            }

                        }

                    }


                }
            }
        }
        return ds;
    }
    private void CompareCurrPageValue(ref int iTotalPages, ref int iCurrPage, HtmlForm frmObj)
    {
        try
        {
            if (iCurrPage > iTotalPages)
            {
                iCurrPage = iTotalPages;
                DynamicDisplayI DDI = new DynamicDisplayI();
                HtmlInputHidden hihObj = (HtmlInputHidden)DDI.FindControl(frmObj.Controls, "hihCurrentPageId");
                hihObj.Value = iTotalPages.ToString();
                DDI = null;
            }
        }
        catch
        {
        }


    }

    private bool DisplayPageWithTree(String strPagesetRowID, HtmlForm frmObj, DynamicDisplayI DDI) //Added BY Dhanapal ON DEC292010
    {
        HDDatabase HDD = new HDDatabase();
        UltraWebTree ut = new UltraWebTree();
        security HDS = new security();
        bool bRead = false;
        bool bCreate = false;
        bool bEdit = false;
        bool bDelete = false;
        HDS.getPagesetRights(strPagesetRowID, ref bRead, ref bCreate, ref bEdit, ref bDelete);
        if (bRead)//If read Permission Then Proced
        {
            PageInfoLoad PIL = new PageInfoLoad();
            DataSet dsePageObj = PIL.GetPageSetPagesSrchInfo(strPagesetRowID);
            DataTable dtaPageSet = dsePageObj.Tables["PageSet"];
            DataTable dtaPage = dsePageObj.Tables["Page"];
            DataTable dtaPageKeys = dsePageObj.Tables["PageKeys"];
            DataTable dtaPageSrch = dsePageObj.Tables["PageSrch"];
            DataTable dtaPageControls = dsePageObj.Tables["Page Controls"];
            DataTable dtaPageMode = dsePageObj.Tables["PageModes"];
            DataTable dtaPageModeFields = dsePageObj.Tables["PageModesFields"];
            if (dtaPageMode.Select("mode = 'TV'").Length > 0) //To Check Whether the Table Contains TREE DATA
            {
                DataRow[] drPageMode = dtaPageMode.Select("Mode = 'TV'");
                string ParentField = "";
                string ChildField = "";
                string strPageModeId = drPageMode[0]["af_row_id"].ToString().Trim();
                if (strPageModeId != "")
                {
                    DataRow[] drPageModeFields = dtaPageModeFields.Select("mode_id = '" + strPageModeId + "'");
                    foreach (DataRow drfieldtype in drPageModeFields)
                    {
                        if (drfieldtype["field_type"].ToString() == "PARENT_NODE")
                        {
                            ParentField = drfieldtype["field"].ToString();
                        }
                        else if (drfieldtype["field_type"].ToString() == "CHILD_NODE")
                        {
                            ChildField = drfieldtype["field"].ToString();
                        }

                    }
                    if (ParentField.Trim() != "" && ChildField.Trim() != "")
                    {
                        HiddenField hfParent = (HiddenField)DDI.FindControl(frmObj.Controls, "hdnParentField");
                        HiddenField hfChild = (HiddenField)DDI.FindControl(frmObj.Controls, "hdnChildField");
                        HiddenField hdnPageSetId = (HiddenField)DDI.FindControl(frmObj.Controls, "hdnPageSetId");

                        if (hfParent != null)
                            hfParent.Value = ParentField;
                        if (hfChild != null)
                            hfChild.Value = ChildField;
                        if (hdnPageSetId != null)
                            hdnPageSetId.Value = strPagesetRowID;

                        TreeViewI bt = new TreeViewI();
                        return bt.GenerateTree(dtaPage, dtaPageSrch, dtaPageKeys, dtaPageControls, ParentField, ChildField, frmObj, bRead, bCreate, bEdit, bDelete, strPagesetRowID);//Added BY DHanapal ON 30DEC2010
                    }
                    else
                    {


                    }

                }
            }
            return true; // you have the permission to read the data
        }
        else
        {
            return false; //Do not Have Permision to read the data
        }


    }


    private void showandhideDiv(HtmlForm frmObj, string divid, bool status, DynamicDisplayI DDI) //Added By Dhanapal On DEC292010
    {
        System.Web.UI.HtmlControls.HtmlGenericControl panel = (System.Web.UI.HtmlControls.HtmlGenericControl)DDI.FindControl(frmObj.Controls, divid);
        if (panel != null)
            panel.Visible = status;
    }

    private bool DisplayPageWithCategory(String strPagesetRowID, HtmlForm frmObj, DynamicDisplayI DDI) //Added By Dhanapal On Jan 24 2011
    {
        HDDatabase HDD = new HDDatabase();
        security HDS = new security();
        bool bRead = false;
        bool bCreate = false;
        bool bEdit = false;
        bool bDelete = false;
        HDS.getPagesetRights(strPagesetRowID, ref bRead, ref bCreate, ref bEdit, ref bDelete);
        if (bRead)//If read Permission Then Proced
        {
            HiddenField hdnPageSetId = (HiddenField)DDI.FindControl(frmObj.Controls , "hdnCategoryPageSetId");
            if (hdnPageSetId != null)
                hdnPageSetId.Value = strPagesetRowID;

            PageInfoLoad PIL = new PageInfoLoad();
            DataSet dsePageObj = PIL.GetPageSetPagesSrchInfo(strPagesetRowID);
            DataTable dtaPageSet = dsePageObj.Tables["PageSet"];
            DataTable dtaPage = dsePageObj.Tables["Page"];
            DataTable dtaPageKeys = dsePageObj.Tables["PageKeys"];
            DataTable dtaPageSrch = dsePageObj.Tables["PageSrch"];
            DataTable dtaPageControls = dsePageObj.Tables["Page Controls"];
            DataTable dtaPageMode = dsePageObj.Tables["PageModes"];
            DataTable dtaPageModeFields = dsePageObj.Tables["PageModesFields"];
            if (dtaPageMode.Select("mode = 'CV'").Length > 0) //To Check Whether the Table Contains TREE DATA
            {
                DataRow[] drPageMode = dtaPageMode.Select("Mode = 'CV'");
                string strPageModeId = drPageMode[0]["af_row_id"].ToString().Trim();
                string groupingField = "";
                if (strPageModeId != "")
                {
                    DataRow[] drPageModeFields = dtaPageModeFields.Select("mode_id = '" + strPageModeId + "'");
                    foreach (DataRow drfieldtype in drPageModeFields)
                    {
                        if (drfieldtype["field_type"].ToString() == "GROUPING")
                        {
                            groupingField = drfieldtype["field"].ToString();
                        }

                    }

                    if (groupingField.Trim() != "")
                    {
                        HiddenField hfgroupingField = (HiddenField)DDI.FindControl(frmObj.Controls, "hdngroupingField");
                        if (hfgroupingField != null)
                        {
                            hfgroupingField.Value = groupingField;
                            CategoryView cv = new CategoryView();
                            return cv.GenerateCategory(dtaPage, dtaPageSrch, dtaPageKeys, dtaPageControls, groupingField, frmObj, bRead, bCreate, bEdit, bDelete, strPagesetRowID, dsePageObj);//Added BY DHanapal ON Jan 24 2011
                        }
                    }

                }

            }
            return true;
        }
        else
        {
            return false;
        }

    }

}
